package com.ericsson.resourceplanner.web;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.http.HttpOutputMessage;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.ericsson.resourceplanner.service.impl.AppUserDetailsService;
import com.ericsson.resourceplanner.utils.ReadLandingPageUtil;
import com.ericsson.resourceplanner.utils.SecurityContextRolesUtils;

/**
 * Handles requests for the application home page.
 */
@Controller
public class LoginController {

	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	
	@Autowired 
	AppUserDetailsService appuserdetailsservice;

	@Autowired 
	//@Resource(name="landingbean")
	ReadLandingPageUtil readLandingPageUtil;
	/*public static void main(String[] args) {
		ApplicationContext cont = new ClassPathXmlApplicationContext("spring/root-context.xml","spring/spring-security.xml","spring/appServlet/servlet-context.xml");
		LoginController lc = cont.getBean("loginController",LoginController.class);
		System.out.println(lc.landingbean);
	}*/
	
	public void setReadLandingPageUtil(ReadLandingPageUtil readLandingPageUtil) {
		this.readLandingPageUtil = readLandingPageUtil;
	}
	
	@Autowired
	SecurityContextRolesUtils securityContextRolesUtils;
	
	@RequestMapping(value = "/home", method ={ RequestMethod.POST,RequestMethod.GET})
	public String mylogin(Locale locale, Model model,HttpServletRequest request) {
		logger.info("Welcome home! The client locale is {}.", locale);


		/*String formattedDate = dateFormat.format(date);

		Collection<? extends GrantedAuthority> c = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
		//SecurityContextHolder.getContext().getAuthentication().getCredentials();
		 */
		String parameter  = request.getParameter("myrole");
		//System.out.println("---------the parameter is:"+parameter);
		model.addAttribute("roleOfUser", parameter );
		return "HomePage";
	}

    @RequestMapping(value="/selectrolelogin", method = RequestMethod.POST)
    public String getLandingPage(HttpServletRequest request)
    {
    	String roledropdown  = request.getParameter("myrole");
    	String page = "";
    	
    	/*if(roledropdown.equals("Admin"))
    		page = "changeRole";
    	else
    		page = "HomePage";*/
    	//page = readLandingPageUtil.getLandingPageName();
    	
    	Map<String, String> map;
    	map = readLandingPageUtil.getLandingPageName();
    	page = map.get(roledropdown);
    	
      	Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    	List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    	authorities.add(new GrantedAuthorityImpl(roledropdown));
    	Authentication newAuth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(),auth.getCredentials(),authorities);
    	SecurityContextHolder.getContext().setAuthentication(newAuth);
    	/*for(String s : sc.getAuthentication().getAuthorities().toString().split(","))
    	{
    		System.out.println("r-------------------->"+s);
    	}*/
    		
    	return page;
    }
	
	@RequestMapping(value = "/login/forgetPassword", method ={ RequestMethod.POST,RequestMethod.GET})
	public String changePassword(Locale locale, Model model,HttpServletRequest request) {
		logger.info("Welcome home! The client locale is {}.", locale);
		return "passwordchange";
	}


	@RequestMapping(value = "/admin", method = RequestMethod.GET)
	public String adminLogin(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		//System.out.println("in /admin of logincontroller--------------------------");
		return "changeRole";
	}

	@RequestMapping(value = "/403", method = RequestMethod.GET)
	public String myError(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		return "Welcome1";
	}

	@RequestMapping(value = "/login/passwordchangedsuccess", method = RequestMethod.POST)
	public String passwordschanged(Locale locale, Model model, HttpServletRequest request) {
		logger.info("Welcome home! The client locale is {}.", locale);
		//UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String userSignum = request.getParameter("userid");
		String userPass = request.getParameter("password");
		String userConfPass = request.getParameter("conpassword"); 
		System.out.println("For pass reset");
		System.out.println(userSignum);
		System.out.println(userPass);
		System.out.println(userConfPass);
		 appuserdetailsservice.insertUserWithChangedPassword(userSignum, userPass);
		return "Welcome1";
	}

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String login(Locale locale, Model model,HttpServletRequest req) {
		logger.info("Welcome home! The client locale is {}.", locale);
		return "login";
		//return "adminpage";
	}

	@RequestMapping(value = "/rolebasedLogin", method = RequestMethod.GET)
	public String roleBasedLogin(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		SecurityContext sc = SecurityContextHolder.getContext();
	    String []role = securityContextRolesUtils.getRoles(sc);
		model.addAttribute("username",sc.getAuthentication().getName());
		model.addAttribute("roleList",role);
		return "rolebasedLogin";
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String ulogin(Locale locale, Model model) {
		return "login";
	}


	@RequestMapping("/logout")
	public String gotoLogout(Model model)
	{
		model.addAttribute("message", "Going to login page");
		return "login";	
	}
}


